package com.luli.service.impl;

import com.luli.entity.Signature;
import com.luli.entity.Users;
import com.luli.service.PdfSignatureService;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.pdfbox.text.PDFTextStripper;
import org.springframework.stereotype.Service;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;

/**
 * 陆离
 * 2024/11/12
 */
@Service
public class PdfSignatureServiceImpl implements PdfSignatureService {
    @Override
    public void signPdf(String inputPdfPath, String outputPdfPath, String signatureImagePath) {
        // 加载要签章的 PDF 文档
        try (PDDocument document = PDDocument.load(new File(inputPdfPath))) {

            // 获取第一页，假设签章放在第一页
            PDPage page = document.getPage(0);

            // 加载签章图片
            PDImageXObject signatureImage = PDImageXObject.createFromFile(signatureImagePath, document);

            // 创建一个内容流对象，用于在页面上绘制内容
            try (PDPageContentStream contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true)) {

                // 设置签章图片的位置和大小（假设在左下角签章）
                float imageX = 50;
                float imageY = 50;
                float imageWidth = 150;
                float imageHeight = 150;

                // 绘制签章图片
                contentStream.drawImage(signatureImage, imageX, imageY, imageWidth, imageHeight);
            }

            // 保存签章后的文档
            document.save(outputPdfPath);
        } catch (InvalidPasswordException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    public void addSignatureToPdf(String inputPdfPath, String outputPdfPath, Signature signature){
        try (PDDocument document = PDDocument.load(new File(inputPdfPath))) {
            PDPageContentStream contentStream = new PDPageContentStream(document, document.getPage(0));
            PDImageXObject pdImage = PDImageXObject.createFromFile(signature.getImagePath(), document);
            contentStream.drawImage(pdImage, signature.getX(), signature.getY(), signature.getWidth(), signature.getHeight());
            contentStream.close();

            document.save(outputPdfPath);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * https://blog.csdn.net/qq_38617531/article/details/83795291?ops_request_misc=&request_id=&biz_id=102&utm_term=pdfbox%E8%8E%B7%E5%8F%96%E5%85%B3%E9%94%AE%E5%AD%97%E9%A1%B5%E7%A0%81&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduweb~default-1-83795291.142^v100^pc_search_result_base4&spm=1018.2226.3001.4187
     * 通过PDFbox获取文章总页数
     *
     * @param filePath:文件路径
     * @return
     * @throws IOException
     */
    public static int getNumberOfPages(String filePath) throws IOException, InterruptedException {
        File file = new File(filePath);
        PDDocument pdDocument = PDDocument.load(new File(filePath));
        int pages = pdDocument.getNumberOfPages();
        pdDocument.close();
        return pages;
    }

    /**
     * 通过PDFbox获取文章内容
     *
     * @param filePath
     * @return
     */
    public static String getContent(String filePath) throws IOException {
        PDFParser pdfParser = new PDFParser(new org.apache.pdfbox.io.RandomAccessFile(new File(filePath), "rw"));
        pdfParser.parse();
        PDDocument pdDocument = pdfParser.getPDDocument();
        String text = new PDFTextStripper().getText(pdDocument);
        pdDocument.close();

        return text;
    }


    /**
     * 通过PDFbox生成文件的缩略图
     *
     * @param filePath：文件路径
     * @param outPath：输出图片路径
     * @throws IOException
     */
    public static void getThumbnails(String filePath, String outPath) throws IOException {
        // 利用PdfBox生成图像
        PDDocument pdDocument = PDDocument.load(new File(filePath));
        PDFRenderer renderer = new PDFRenderer(pdDocument);

        // 构造图片
        BufferedImage img_temp = renderer.renderImageWithDPI(0, 30, ImageType.RGB);
        // 设置图片格式
        Iterator<ImageWriter> it = ImageIO.getImageWritersBySuffix("png");
        // 将文件写出
        ImageWriter writer = (ImageWriter) it.next();
        ImageOutputStream imageout = ImageIO.createImageOutputStream(new FileOutputStream(outPath));
        writer.setOutput(imageout);
        writer.write(new IIOImage(img_temp, null, null));
        img_temp.flush();
        imageout.flush();
        imageout.close();
        //Warning: You did not close a PDF Document
        pdDocument.close();
    }


    public static void main(String[] args) throws IOException, InterruptedException {
        System.out.println(getNumberOfPages("C:\\Users\\lenovo\\Desktop\\江天兰台\\电子签章测试\\日志提交.pdf"));
        System.out.println("===================");
        System.out.println(getContent("C:\\Users\\lenovo\\Desktop\\江天兰台\\电子签章测试\\日志提交.pdf"));
        getThumbnails("C:\\Users\\lenovo\\Desktop\\江天兰台\\电子签章测试\\日志提交.pdf","C:\\Users\\lenovo\\Desktop\\江天兰台\\电子签章测试\\电子签章缩略.png");
    }
}
